package com.example.learning.demo.zookeeper.watcher;

import com.example.learning.demo.zookeeper.config.ZookeeperConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.Arrays;

/**
 * ClassName ZookeeperWatcher
 * Description
 *
 * @author <a href="mailto:xuxb@zjport.gov.cn">xuxb</a>
 * @date 2021/5/20 8:10
 * @since 1.0
 */
@Slf4j
@Component
public class ZookeeperWatcher implements Watcher {

    @Autowired
    private ZookeeperConfig config;

    private ZooKeeper zooKeeper;

    public ZookeeperWatcher() {

    }

    @PostConstruct
    void init(){
        ZooKeeper zooKeeper = null;
        try {
            zooKeeper = new ZooKeeper(config.getConnectString(), config.getTimeout(), this);
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.zooKeeper = zooKeeper;
    }

    public String create(String path, String data, CreateMode mode) {
        try {
            return zooKeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, mode);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getData(String path) {
        try {
            return Arrays.toString(zooKeeper.getData(path, true, null));
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    /** @return the zooKeeper */
    public ZooKeeper getZooKeeper() {
        return zooKeeper;
    }

    @Override
    public void process(WatchedEvent event) {
        log.warn(event.getPath()+"####"+event.getType());
        try {
            if (null != zooKeeper.exists("/qingquan", true)){
                log.info("内容："+zooKeeper.getData("/qingquan", true, null));
            }
        } catch (KeeperException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
